<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\View;
use think\Cookie;
use think\Request;
use Think\Upload;
use app\index\model\IndexModel;
class Goods extends Controller{
	public function index(){
		$view=new View();
		return $view->fetch();
	}
	
	public function goods(){
		$view=new View();
		$m=new IndexModel;
 		$uid=Cookie::get("user_id");
		$powers=$m->getPowersByUid($uid);
		$view->assign('powers',$powers);
		
		$store_id=Cookie::get('store_id');
		if(empty($store_id)){
			$this->error('店铺信息错误','Index/login');exit;
		}
		$wh=array(
			'store_id'=>$store_id,
			'gcat_status'=>1
		);
		//取出分类
		$categorys=Db::name('waimai_goods_category')->where($wh)->order('gcat_sort')->select();
		foreach($categorys as $key=>$c){
			//根据分类取出对应菜品
			$whg=array(
			'gcat_id'=>$c['gcat_id'],
			'status'=>1
			);
			$goods=Db::name('waimai_goods')->where($whg)->select();
				foreach ($goods as $k=>$goodsInfo){
	    		$tmp_pic_arr = explode(';', $goodsInfo['image']);
	    		//dump($tmp_pic_arr);
	    		$goods[$k]['list_pic'] = get_image_by_path($tmp_pic_arr['0'], 's');
	    		//echo "list_pic". $goods[$k]['list_pic'];
	    		}
			$carray[$c['gcat_id']]['categorys']=$c;
			$carray[$c['gcat_id']]['goods']=$goods;
		}
		//取出回收站的菜品
		$wht=array(
			'status'=>0		
		);
		$trash=Db::name('waimai_goods')->where($wht)->select();
		foreach ($trash as $k=>$vo){
	    		$tmp_pic_arr = explode(';', $vo['image']);
	    		//dump($tmp_pic_arr);
	    		$trash[$k]['list_pic'] = get_image_by_path($tmp_pic_arr['0'], 's');
	    		//echo "list_pic". $goods[$k]['list_pic'];
	    }
		//dump($carray);
		$view->assign('list',$carray);
		$view->assign('trash',$trash);
		return $view->fetch();
	}
	public function goods_update($goods_id=0){
		$view=new View();
		$m=new IndexModel;
 		$uid=Cookie::get("user_id");
		$powers=$m->getPowersByUid($uid);
		$view->assign('powers',$powers);
		$store_id=Cookie::get('store_id');
		if(empty($store_id) && $goods_id==0){
			$this->error('店铺信息错误','Index/login');exit;
		}
		$wh=array(
			'store_id'=>$store_id,
			'gcat_status'=>1
		);
		//取出分类
		$categorys=Db::name('waimai_goods_category')->where($wh)->select();
		
			$goods=Db::name('waimai_goods')->where(array('goods_id'=>$goods_id))->find();
			$tmp_pic_arr = explode(';', $goods['image']);
	    	$goods['list_pic'] = get_image_by_path($tmp_pic_arr['0'], -1);
	    	$goods['old_img'] =$tmp_pic_arr['0'];
	    	$goods['gjson']=json_decode($goods['gjson']);
	    	$goods['gweight']=json_decode($goods['gweight']);
			foreach($tmp_pic_arr as $key=>$value){
				$goods['pic'][$key]['title'] = $value;
				$goods['pic'][$key]['url'] = get_image_by_path($value, 's');
			}
		$goods['gbody']=str_replace('src="','src="http://www.kykxmk.com',$goods['gbody']);
		$view->assign('categorys',$categorys);
		$view->assign('goods',$goods);

		return $view->fetch();
	}
	public function goods_update2(){
	$m=new IndexModel;
 		$uid=Cookie::get("user_id");
		$powers=$m->getPowersByUid($uid);
		$view->assign('powers',$powers);
		
        $files = array();
        $success = 0;    //用户统计有多少张图片上传成功了
        
        foreach ($_FILES as $item) {
            $index = count($files);

            $files[$index]['srcName'] = $item['name'];    //上传图片的原名字
            $files[$index]['error'] = $item['error'];    //和该文件上传相关的错误代码
            $files[$index]['size'] = $item['size'];        //已上传文件的大小，单位为字节
            $files[$index]['type'] = $item['type'];        //文件的 MIME 类型，需要浏览器提供该信息的支持，例如"image/gif"
            $files[$index]['success'] = false;            //这个用于标志该图片是否上传成功
            $files[$index]['path'] = '';                //存图片路径

            // 接收过程有没有错误
            if($item['error'] != 0) continue;
            //判断图片能不能上传
            if(!is_uploaded_file($item['tmp_name'])) {
                $files[$index]['error'] = 8000;
                continue;
            }
            //扩展名
            $extension = '';
            if(strcmp($item['type'], 'image/jpeg') == 0) {
                $extension = '.jpg';
            }
            else if(strcmp($item['type'], 'image/png') == 0) {
                $extension = '.png';
            }
            else if(strcmp($item['type'], 'image/gif') == 0) {
                $extension = '.gif';
            }
            else {
                //如果type不是以上三者，我们就从图片原名称里面去截取判断去取得(处于严谨性)    
                $substr = strrchr($item['name'], '.');
                if(FALSE == $substr) {
                    $files[$index]['error'] = 8002;
                    continue;
                }

                //取得元名字的扩展名后，再通过扩展名去给type赋上对应的值
                if(strcasecmp($substr, '.jpg') == 0 || strcasecmp($substr, '.jpeg') == 0 || strcasecmp($substr, '.jfif') == 0 || strcasecmp($substr, '.jpe') == 0 ) {
                    $files[$index]['type'] = 'image/jpeg';
                }
                else if(strcasecmp($substr, '.png') == 0) {
                    $files[$index]['type'] = 'image/png';
                }
                else if(strcasecmp($substr, '.gif') == 0) {
                    $files[$index]['type'] = 'image/gif';
                }
                else {
                    $files[$index]['error'] = 8003;
                    continue;
                }
                $extension = $substr;
            }

            //对临时文件名加密，用于后面生成复杂的新文件名
            $md5 = md5_file($item['tmp_name']);
            //取得图片的大小
            $imageInfo = getimagesize($item['tmp_name']);
            $rawImageWidth = $imageInfo[0];
            $rawImageHeight = $imageInfo[1];

            //设置图片上传路径，放在upload文件夹，以年月日生成文件夹分类存储，
            //rtrim(base_url(), '/')其实就是网站的根目录，大家自己处理
            $path = rtrim(base_url(), '/') . '/upload/' . date('Ymd') . '/';
            //确保目录可写
            ensure_writable_dir($path);
            //文件名
            $name = "$md5.0x{$rawImageWidth}x{$rawImageHeight}{$extension}";
            //加入图片文件没变化到，也就是存在，就不必重复上传了，不存在则上传
            $ret = file_exists($path . $name) ? true : move_uploaded_file($item['tmp_name'], $serverPath . $name);
            if($ret === false) {
                $files[$index]['error'] = 8004;
                continue;
            }
            else {
                $files[$index]['path'] = $path . $name;        //存图片路径
                $files[$index]['success'] = true;            //图片上传成功标志
                $files[$index]['width'] = $rawImageWidth;    //图片宽度
                $files[$index]['height'] = $rawImageHeight;    //图片高度
                $success ++;    //成功+1
            }
        }

        //将图片已json形式返回给js处理页面  ，这里大家可以改成自己的json返回处理代码
        echo json_encode(array(
            'total' => count($files),
            'success' => $success,
            'files' => $files,
        ));
    
}

	
	
	public function goods_delete($goods_id=0){
		$m=new IndexModel;
 		$uid=Cookie::get("user_id");
		$powers=$m->getPowersByUid($uid);
		$view->assign('powers',$powers);
		
		$view=new View();
		$store_id=Cookie::get('store_id');
		if(empty($store_id)){
			$this->error('店铺信息错误','Index/login');exit;
		}
		//取出所有菜品
		$wh=array(
			'store_id'=>$store_id,
			'goods_id'=>$goods_id,
		);
		$data=[
			'status'=>0
		];
		Db::name('Waimai_goods')->where($wh)->update($data);
		$this->redirect('Goods/goods');
	}
	
public function ajax_upload_picmore(){
	
		$store_id=Cookie::get('store_id');
	
$extArr = array("jpg", "png", "gif");

	if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
		$name = $_FILES['photoimg1']['name'];
		$size = $_FILES['photoimg1']['size'];
		$old_img=$_POST['old_pic'];
			if(!empty($old_img)){
				$imgarray=explode(",",$old_img);
				$upload_dir =  $imgarray['0'] . '/';
			}else{
				$rand_num = mt_rand(10, 99) . '/' . substr($store_id, 0, 3) . '/' . substr($store_id, 3, 3) . '/' . substr($store_id, 6, 3);
	            $upload_dir =  $rand_num . '/';
			}
		
		
		if(empty($name)){
			echo '请选择要上传的图片';
			exit;
		}
		
		if($size>(500*1024)){
			echo '图片大小不能超过100KB';
			exit;
		}
		$type = strstr($name, '.');  
					        if ($type != ".gif" && $type != ".jpg" && $type != ".png") {  
					            echo '图片格式不对！';  
					            exit;  
					        }  
		$image_name = time().rand(100,999) . $type;
		$tmp = $_FILES['photoimg1']['tmp_name'];
		//上传路径  
		$pic_path = 'upload/waimai/' . $image_name;  
		if(move_uploaded_file($tmp, $pic_path)){
			echo '<img src="/'.$pic_path.'"  class="preview1">';
		}else{
			echo '上传出错了！';
		}
	
		
		exit;
	}
exit;
}

	
	public function ajax_upload_pic(){
		$store_id=Cookie::get('store_id');
		$old_img=$_POST['old_img'];
		if(!empty($old_img)){
			$imgarray=explode(",",$old_img);
			$upload_dir =  $imgarray['0'] . '/';
		}else{
			$rand_num = mt_rand(10, 99) . '/' . substr($store_id, 0, 3) . '/' . substr($store_id, 3, 3) . '/' . substr($store_id, 6, 3);
            $upload_dir =  $rand_num . '/';
		}
		 $picname = $_FILES['mypic']['name'];  
				    $picsize = $_FILES['mypic']['size'];  
				    if ($picname != "") {  
				        if ($picsize > 1024000*30) {  
				            echo '图片大小不能超过30M';  
				            exit;  
				        }  
				        $type = strstr($picname, '.');  
				        if ($type != ".gif" && $type != ".jpg" && $type != ".png") {  
				            echo '图片格式不对！';  
				            exit;  
				        }  
				        $rand = rand(100, 999);  
				        $pics = $upload_dir . "s_". date("YmdHis") . $rand . $type;  
				        //上传路径  
				        $pic_path = 'upload/waimai/' . $pics;  
				        $result=move_uploaded_file($_FILES['mypic']['tmp_name'], $pic_path);  
				    }  
				    $size = round($picsize/1024,2);  
				    $arr = array(  
				        'name'=>$picname,  
				        'pic'=>$pics,  
				        'size'=>$size
				    );  
		  
		  		  echo json_encode($arr);  
	}
	
	public function ajax_del_pic(){
	 $filename = $_POST['imagename'];  
		    if(!empty($filename)){  
		        unlink('upload/waimai/'.$filename);  
		        echo '1';  
		    }else{  
		        echo '删除失败.';  
		    }  
	}
	
	
	public function categorys(){
		$view=new View();
		$m=new IndexModel;
 		$uid=Cookie::get("user_id");
		$powers=$m->getPowersByUid($uid);
		$view->assign('powers',$powers);
		
		$store_id=Cookie::get('store_id');
		$store_name=Cookie::get('store_name');
		if(empty($store_id)){
			$this->error('店铺信息错误','Index/login');exit;
		}
		//取出所有菜品
		$wh=array(
			'store_id'=>$store_id,
			'gcat_status'=>1
		);

		$categorys=Db::name('Waimai_goods_category')->where($wh)->order('gcat_sort')->select();
		$view->assign('list',$categorys);
		$view->assign('store_name',$store_name);
		return $view->fetch();
	}
	public function category_update($gcat_id=0){
		$view=new View();
		$m=new IndexModel;
 		$uid=Cookie::get("user_id");
		$powers=$m->getPowersByUid($uid);
		$view->assign('powers',$powers);
		
		$store_id=Cookie::get('store_id');
		$store_name=Cookie::get('store_name');
		if(empty($store_id)){
			$this->error('店铺信息错误','Index/login');exit;
		}
		//取出所有菜品
		$wh=array(
			'store_id'=>$store_id,
			'gcat_id'=>$gcat_id,
		);

		$categorys=Db::name('Waimai_goods_category')->where($wh)->find();
		$view->assign('vo',$categorys);
		$view->assign('store_name',$store_name);
		return $view->fetch();
	}
	public function category_update2(){
		$view=new View();
		$m=new IndexModel;
 		$uid=Cookie::get("user_id");
		$powers=$m->getPowersByUid($uid);
		$view->assign('powers',$powers);
		
		$store_id=Cookie::get('store_id');
		$store_name=Cookie::get('store_name');
		if(empty($store_id) && !(Request::instance()->isPost())){
			$this->error('店铺信息错误','Index/login');exit;
		}
		
		$gcat_id=$_POST['gcat_id'];
		$gcat_name=$_POST['gcat_name'];
		$gcat_pinyin=$_POST['gcat_pinyin'];
		$gcat_sort=$_POST['gcat_sort'];
		$last_time=strtotime(date("Y-m-d H:i:s"));
		//取出所有菜品
		$wh=array(
			'store_id'=>$store_id,
			'gcat_id'=>$gcat_id,
		);
		$data=[
			'gcat_name'=>$gcat_name,
			'gcat_pinyin'=>$gcat_pinyin,
			'gcat_sort'=>$gcat_sort,
			'last_time'=>$last_time
		];
		Db::name('Waimai_goods_category')->where($wh)->update($data);
		$this->redirect('Goods/categorys');
	}
	public function category_delete($gcat_id=0){
		$view=new View();
		$m=new IndexModel;
 		$uid=Cookie::get("user_id");
		$powers=$m->getPowersByUid($uid);
		$view->assign('powers',$powers);
		
		$store_id=Cookie::get('store_id');
		$store_name=Cookie::get('store_name');
		if(empty($store_id)){
			$this->error('店铺信息错误','Index/login');exit;
		}
		//取出所有菜品
		$wh=array(
			'store_id'=>$store_id,
			'gcat_id'=>$gcat_id,
		);
		$data=[
			'gcat_status'=>0
		];
		Db::name('Waimai_goods_category')->where($wh)->update($data);
		$this->redirect('Goods/categorys');
	}
	public function category_add(){
		$view=new View();
		$m=new IndexModel;
 		$uid=Cookie::get("user_id");
		$powers=$m->getPowersByUid($uid);
		$view->assign('powers',$powers);
		
		$store_id=Cookie::get('store_id');
		$store_name=Cookie::get('store_name');
		if(empty($store_id)){
			$this->error('店铺信息错误','Index/login');exit;
		}
		return $view->fetch();
	}
	public function category_add2(){
		$view=new View();
		$m=new IndexModel;
 		$uid=Cookie::get("user_id");
		$powers=$m->getPowersByUid($uid);
		$view->assign('powers',$powers);
		
		$store_id=Cookie::get('store_id');
		$store_name=Cookie::get('store_name');
		if(empty($store_id) && !(Request::instance()->isPost())){
			$this->error('店铺信息错误','Index/login');exit;
		}
		
		$gcat_name=$_POST['gcat_name'];
		$gcat_pinyin=$_POST['gcat_pinyin'];
		$gcat_sort=$_POST['gcat_sort'];
		$create_time=strtotime(date("Y-m-d H:i:s"));
		$last_time=strtotime(date("Y-m-d H:i:s"));
		$mer=Db::name('merchant_store')->field('mer_id')->where(array('store_id'=>$store_id))->find();
		$mer_id=$mer['mer_id'];
		//取出所有菜品
		
		$data=[
			'gcat_name'=>$gcat_name,
			'gcat_pinyin'=>$gcat_pinyin,
			'gcat_sort'=>$gcat_sort,
			'gcat_status'=>1,
			'create_time'=>$create_time,
			'last_time'=>$last_time,
			'store_id'=>$store_id,
			'mer_id'=>$mer_id,
		];
		Db::name('Waimai_goods_category')->insert($data);
		$this->redirect('Goods/categorys');
	}
}
?>